package com.fxcalibre.syncservices.imdb.parser;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

public class ImdbDetailParser
{
	public static HashMap<String, String> parse(String htmInput)
	{
		HashMap<String, String> result = new HashMap<>();

		Document doc = Jsoup.parse(htmInput);

		Elements content = doc.select("h1[itemprop$=name]");

		// getElementsByAttributeValue("itemProp","name");
		for (Iterator iterator = content.iterator(); iterator.hasNext();)
		{
			Element element = (Element) iterator.next();
			result.put("name", element.childNode(0).toString().trim());
			if(element.select("span.title-extra").size() > 0)
			{
				result.put("orName",element.select("span.title-extra").get(0).childNode(0).toString().trim());
			}
		}

		content = doc.select("tbody  span[itemprop$=director]");

		// getElementsByAttributeValue("itemProp","name");
		for (Iterator iterator = content.iterator(); iterator.hasNext();)
		{
			Element element = (Element) iterator.next();
			System.out.println(element.text());
			result.put("director", element.text());
		}
		//
		// content = doc.select("tbody  span[itemprop$=actors]");
		//
		// // getElementsByAttributeValue("itemProp","name");
		// for (Iterator iterator = content.iterator(); iterator.hasNext();)
		// {
		// Element element = (Element) iterator.next();
		// System.out.println(element.text());
		// }

		// Elements links = content.getElementsByTag("a");
		// for (Element link : links)
		// {
		// String linkHref = link.attr("href");
		// String linkText = link.text();
		// }
		//
		// Elements links2 = doc.select("a[href]"); // a with href
		// Elements pngs = doc.select("img[src$=.png]");
		// // img with src ending .png
		//
		// Element masthead = doc.select("div.masthead").first();
		// // div with class=masthead
		//
		// Elements resultLinks = doc.select("h3.r > a"); // direct a after h3
		// result.put("title", getTitle(htmInput));

		return result;
	}

	private static String getTitle(String result)
	{
		String title = null;
		int start = result.indexOf("itemprop=\"name\">");

		if (start > 0)
		{
			start += 16;
			int end = result.indexOf("<", start);
			if (end > 0)
			{
				title = new String(result.substring(start, end)).trim();
			}
		}

		return title;
	}

}
